<template>
  <div class="">
    <div v-if="showFileList">
      <el-upload
        class=""
        :file-list="fileList"
        :show-file-list="showFileList"
        :limit="limit"
        :accept="accept"
        list-type="picture-card"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :on-preview="uploadPreview"
        :on-remove="uploadRemove"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <i :class="uploadIcon"></i>
      </el-upload>
    </div>
    <div v-else>
      <el-upload
        v-if="isButton"
        class=""
        :show-file-list="showFileList"
        :accept="accept"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <el-button type="primary" icon="el-icon-upload">{{buttonText}}</el-button>
      </el-upload>
      <el-upload
        v-else
        class="single-image-uploader"
        :show-file-list="showFileList"
        :accept="accept"
        :headers="uploadHeaders"
        :action="uploadAction"
        :data="uploadData"
        :before-upload="uploadBefore"
        :on-success="uploadSuccess"
        :on-error="uploadError"
      >
        <img v-if="isShowFile && single_file_url" :src="single_file_url" class="single-image">
        <i v-else :class="uploadIcon + ' single-image-uploader-icon'"></i>
      </el-upload>
    </div>

    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {getAdminToken} from "@/utils/auth"
import {uploadURL} from '@/api/admin/common'

export default {
  name: 'FileUpload',
  props: {
    // 多文件
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    // 单文件
    singleFile: {
      type: Object,
      default() {
        return {
          url: '',
          path: ''
        }
      }
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 多文件上传数量
    limit: {
      type: Number,
      default: 9
    },
    // 上传图片大小最大限制(单位：KB)
    imageMaxSize: {
      type: Number,
      default: 500
    },
    // 上传文件大小最大限制(单位：M)
    maxSize: {
      type: Number,
      default: 20
    },
    // 上传文件类型
    accept: {
      type: String,
      default: 'image/jpeg, image/png, image/gif'
    },
    uploadData: {
      type: Object,
      default() {
        return {
          folder: 'default',
          place: 'qiniu',
          multi: this.showFileList,
          total_count: this.limit,
          count: 0
        }
      }
    },
    uploadIcon: {
      type: String,
      default: 'el-icon-plus'
    },
    // 是否要显示文件
    isShowFile: {
      type: Boolean,
      default: true
    },
    // 是否按钮上传
    isButton: {
      type: Boolean,
      default: false
    },
    // 按钮上传对应按钮名称
    buttonText: {
      type: String,
      default: '选择文件'
    },
  },
  data() {
    return {
      loading: '',
      /*fileList: [
        //{name:'', url: ''}
      ],*/
      single_file_url: '',

      uploadHeaders: {AdminToken: getAdminToken()},
      uploadAction: uploadURL(), // 文件上传地址
      /*uploadData: {
        type: 'image'
      },*/
      dialogImageVisible: false,
      dialogImageUrl: '',
    }
  },
  watch: {
    singleFile: function (val, oldval) {
      //console.log(val, oldval)
      if (val) {
        this.single_file_url = val.url
      }
    }
  },
  created() {
    //console.log(this.fileList)
    if (this.singleFile && this.singleFile.url) {
      this.single_file_url = this.singleFile.url
    }
  },
  methods: {
    uploadBefore(file) {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      //let extArr = this.accept.split(',')
      const imageAccept = 'image/jpeg, image/png, image/gif'
      const isFileExt = this.accept.includes(file.type)
      let isFileSize = true
      if (!isFileExt) {
        this.loading.close()
        this.$message.warning('文件格式不正确!')
      } else {
        if (imageAccept.includes(file.type)) {
          isFileSize = file.size / 1024 < this.imageMaxSize
          if (!isFileSize) {
            this.loading.close()
            this.$message.warning('图片大小不能超过 ' + this.imageMaxSize + 'KB!')
          }
        } else {
          isFileSize = file.size / 1024 / 1024 < this.maxSize
          if (!isFileSize) {
            this.loading.close()
            this.$message.warning('文件大小不能超过 ' + this.maxSize + 'M!')
          }
        }
      }

      return isFileExt && isFileSize
    },
    uploadSuccess(res, file) {
      if (res.status === 1) {
        if (this.showFileList) {
          this.fileList.push({
            id: new Date().getTime(),
            name: '',
            url: res.data.full_filepath,
            path: res.data.filepath
          })
        } else {
          if (this.isShowFile) {
            this.single_file_url = res.data.full_filepath
          }
          this.singleFile.url = res.data.full_filepath
          //this.singleFile.url = URL.createObjectURL(file.raw)
          this.singleFile.path = res.data.filepath
        }

        this.uploadCBK()
        this.loading.close()
        this.$message.success(res.msg)
      } else {
        this.loading.close()
        this.$message.error(res.msg)
      }
    },
    uploadError(res) {
      this.loading.close()
      this.$message.error(res.msg || '上传出错')
    },
    uploadRemove(file, fileList) {
      //this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
      var index = this.fileList.indexOf(file)
      if (index !== -1) {
        this.fileList.splice(index, 1)
      }
      this.uploadCBK()
    },
    uploadPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    // 上传回调
    uploadCBK() {
      //console.log(this.fileList)
      if (this.showFileList) {
        this.$emit('uploadCallback', this.fileList)
      } else {
        this.$emit('uploadCallback', this.singleFile)
      }
    }
  }
}
</script>
